﻿using System;
using System.Windows.Forms;
using Krile.Kernel;
using Krile.Kernel.WindowsEx;

namespace Twinkle.Dialogs.Account
{
    public partial class OAuthRequest : Form
    {
        Data.Account acc;
        Tweak.CredentialProviders.OAuth oauth;
        public OAuthRequest()
        {
            InitializeComponent();
            oauth = null;
        }

        public OAuthRequest(Data.Account ac)
            :this()
        {
            acc = ac;
            ac.UserToken = String.Empty;
            ac.UserSecret = String.Empty;
            oauth = ac.CredentialProvider as Tweak.CredentialProviders.OAuth;
            if(oauth == null)
                throw new ArgumentException("Account is not using OAuth.");
        }

        private void oauthLogo_Click(object sender, EventArgs e)
        {
            Bridge.CommonOperation.CallBrowser("http://oauth.net/");
        }

        string reqToken = null;
        private void openBrowserBtn_Click(object sender, EventArgs e)
        {

            var url = oauth.GetProviderAuthUrl(out reqToken);
            if (String.IsNullOrEmpty(url) || String.IsNullOrEmpty(reqToken))
            {
                MessageBoxEx.Show("OAuth negotiation error.", "OAuth error", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Error);
            }
            else
            {
                Bridge.CommonOperation.CallBrowser(url);
                doVerify.Enabled = true;
            }
        }

        private void doVerify_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(verificationCode.Text))
            {
                MessageBoxEx.Show("Verification code is invalid.", "OAuth error", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Error);
            }
            else
            {
                var verify = verificationCode.Text.TrimStart(' ').TrimEnd(' ');
                string usrid = null;
                if (!oauth.GetAccessToken(reqToken, verify, out usrid))
                {
                    MessageBoxEx.Show("Verify failed. Please retry!", "OAuth error", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Error);
                    doVerify.Enabled = false;
                    return;
                }
                acc.UserId = usrid;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
    }
}
